package com.ternnetwork.workflow.controller;

import java.io.InputStream;
import java.security.Principal;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.workflow.dto.HistoricProcessInstanceQueryDto;
import com.ternnetwork.workflow.service.ProcessInstanceService;



/**
 * 流程实例控制器
 * @author xuwenfeng
 *
 */
@Controller
@RequestMapping("/process/instance/*")
public class ProcessInstanceController {
	
	
	@Autowired
	private ProcessInstanceService processInstanceService;
	
	
	
	
	/**
	 * 获取流程实例启动的表单字段
	 * @param processDefinitionId
	 * @return
	 */
	@RequestMapping("/getStartFormData")
	public @ResponseBody BaseResponse getStartFormData(String processDefinitionId) {
		return processInstanceService.getStartFormData(processDefinitionId);
	}
	
	
	/**
	 * 启动一个流程实例
	 * @param user
	 * @param processDefinitionId
	 * @param request
	 * @return
	 */
	@RequestMapping("/start")
	public @ResponseBody BaseResponse start(Principal user,String processDefinitionId,HttpServletRequest request) {
		Map<String,String[]> map=request.getParameterMap();
		return processInstanceService.startProcessInstanceByKey(user.getName(),processDefinitionId,map);
	}
	
	
	
	@RequestMapping("/delete")
    public @ResponseBody BaseResponse delete(String id) {
       	return processInstanceService.delete(id);
    }
    
    
	
	/**
	 * 查找所有流程实例
	 * @param pageable
	 * @param dto
	 * @return
	 */
	@RequestMapping("/findByPage")
	public @ResponseBody BaseResponse findByPage(@PageableDefault Pageable pageable,HistoricProcessInstanceQueryDto dto) {
		return processInstanceService.findByPage(pageable, dto);
	}
	
	
	
	
	/**
	 * 查找个人经办的所有流程实例
	 * @param pageable
	 * @param dto
	 * @return
	 */
	@RequestMapping("/findForPersonalByPage")
	public @ResponseBody BaseResponse findForPersonalByPage(Principal user,@PageableDefault Pageable pageable,HistoricProcessInstanceQueryDto dto) {
		dto.setUserName(user.getName());
		return processInstanceService.findByPage(pageable, dto);
	}
	
	
	/**
	 * 获取流程实例图
	 * @param response
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping("/getDiagram")
	public void getDiagram(HttpServletResponse response,String id) throws Exception{
			ServletOutputStream out = response.getOutputStream();
			InputStream  image=processInstanceService.getDiagram(id);
			response.setContentLength(image.available());
			int s;
			while((s=image.read())!=-1){
				out.write(s);
			}
	        out.close();
	}

}
